﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using PIM.API;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class MealPlanDetails : System.Web.UI.Page
{
    PIMService pimService = new PIMService();
    private int _MealPlanId = 0;
    private string UserIdOfMealPlan = "";
    private const string pathUpload = "../Uploads/MealPlans";
    private const string pathSave = "Uploads/MealPlans";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["MealPlanId"] != null)
        {
            
            _MealPlanId = Convert.ToInt32(Request.QueryString["MealPlanId"].ToString());
            if (Session["Userid"] != null)
            {
                if (!IsPostBack)
                {
                    fillMealPlan(_MealPlanId);
                    btnEdit.Visible = true;
                    btnUpload.Visible = false;
                    
                }
            }
            else
            {
                if (!IsPostBack)
                {
                    fillMealPlan(_MealPlanId);
                }
            }
            sharefb();
            //shareGoogle();
        }
        HtmlMeta tag = new HtmlMeta();
        tag.Attributes.Add("property", "og:title");
        tag.Content = txtMealPlanName.Text;
        Page.Header.Controls.Add(tag);
        HtmlMeta tagDesc = new HtmlMeta();
        tagDesc.Attributes.Add("property", "og:description");
        tagDesc.Content = txtDescription.Text;
        Page.Header.Controls.Add(tagDesc);
        HtmlMeta tagUrl = new HtmlMeta();
        tagUrl.Attributes.Add("property", "og:url");
        tagUrl.Content = Request.Url.AbsoluteUri;
        Page.Header.Controls.Add(tagUrl);
        HtmlMeta tagImage = new HtmlMeta();
        tagImage.Attributes.Add("property", "og:image");
        tagImage.Content = hdLinkImage.Value;
        Page.Header.Controls.Add(tagImage);
        HtmlMeta tagId = new HtmlMeta();
        tagId.Attributes.Add("property", "fb:app_id");
        tagId.Content = "208238106017076";
        Page.Header.Controls.Add(tagId);
        
    }

    private void sharefb()
    {
        string url = Request.Url.AbsoluteUri;
        string facebooklink = "http://www.facebook.com/sharer.php?u=" + url;
        lnkFacebook.HRef = facebooklink;
        lnkGoogle.HRef = "https://plus.google.com/share?url=" + url;
        lnkTwitter.HRef = "https://twitter.com/intent/tweet?text=" + lblMealPlanName.Text + "&url=" + url;
        lnkEmail.HRef = "mailto:?Subject=Meal Plan " + txtMealPlanName.Text + "&body=Please check out meal plan " + lblMealPlanName.Text
            + "%0ALink: " + url;
    }


    private void fillMealPlan(int mealPlanID)
    {
        StringBuilder log = new StringBuilder();
        //log.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Load Meal Plan] Start");
        try
        {
            PIM.API.MealPlan lMealPlan = pimService.GetMealPlanByMealPlanId(mealPlanID.ToString());
            txtMealPlanName.Text = lMealPlan.MealPlanName;
            txtDescription.Text = lMealPlan.Description;
            lblMealPlanName.Text = lMealPlan.MealPlanName;
            lblDescription.Text = lMealPlan.Description;
            hdImage.Value = lMealPlan.MealPlanPhoto;
            checkUser.Value = lMealPlan.UserID.ToString();
            ratingStar.Value = lMealPlan.MealPlanRating.ToString();
            Checkbox1.Checked = lMealPlan.isShared;
            chIsPublish.Checked = lMealPlan.isShared;
            txtBasic.Text = lMealPlan.BasicInfo;
            lblBasic.Text = lMealPlan.BasicInfo;
            //if (!string.IsNullOrEmpty(lblBasic.Text))
            //{
            //    lblBasic.Attributes.Add("class", "bg01 bg02 bg03 clearfix");
            //}
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
            if (!string.IsNullOrEmpty(lMealPlan.MealPlanPhoto))
                Image2.Src = "../" + lMealPlan.MealPlanPhoto;
            else
                Image2.Src = "images/MealPlanDefault.jpg";
            //log.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Load Meal Plan] Success");
            hdLinkImage.Value = Common1.ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/../" + lMealPlan.MealPlanPhoto), false);
        }
        catch (Exception ex)
        {
            //log.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Load Meal Plan] Error: " + ex.Message);
        }

        //log.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Load Meal Plan] End");
        //Common.Logger.WriteLog(log.ToString(), "MealPlanDetail");
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        StringBuilder logSave = new StringBuilder();
        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Start");
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
        try
        {
            string userId = "";
            string[] arrayRecipeId = hdRecipeId.Value.Split(',');
            if (Session["Userid"] != null)
                userId = Session["Userid"].ToString();
            PIM.API.MealPlan mealPlan = pimService.GetMealPlanByMealPlanId(_MealPlanId.ToString());
            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Load meal plan with mealplanid=" + _MealPlanId.ToString());
            string location = "";
            string path = "";
            string nextID = pimService.GetNextID();
  
            

            if (!string.IsNullOrEmpty(userId))
            {
                int _idUser = Convert.ToInt32(userId);
                if (mealPlan.UserID == _idUser)
                {
                    if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                    {
                        if (File.Exists(Server.MapPath(mealPlan.MealPlanPhoto)))
                        {
                            File.Delete(Server.MapPath(mealPlan.MealPlanPhoto));

                        }
                        string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                        location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                        path = pathSave + "/" + nextID + fn;
                        try
                        {
                            System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                            if (image.Size.Width > 700)
                            {
                                Common1.ResizeImage(image, 700, location);
                            }
                            else
                            {
                                Common1.ResizeImage(image, image.Size.Width, location);
                            }
                        }
                        catch (Exception ex)
                        {
                            Response.Write("Error: " + ex.Message);
                        }
                    }
                    else
                    {
                        path = mealPlan.MealPlanPhoto;
                    }

                    //logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update meal plan of my self with userid=" + mealPlan.UserID.ToString());
                    //if (string.IsNullOrEmpty(hdImage.Value))
                    //{
                    //    hdImage.Value = mealPlan.MealPlanPhoto;
                    //    logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Set image value to hdImage");
                    //}
                    string result = pimService.UpdateMealPlan(mealPlan.MealPlanID, mealPlan.UserID, mealPlan.CreatedUserID, mealPlan.ParentUserId,
                        txtMealPlanName.Text, Checkbox1.Checked, mealPlan.canCopy, mealPlan.NoOfReview, mealPlan.MealPlanRating, mealPlan.AvgCalPerDay,
                        mealPlan.EstCostPerDay, path, txtDescription.Text, txtBasic.Text);
                    Image2.Src = "/" + path;
                    //Update Recipe in MealPlanDetail
                    if (result.Equals("True"))
                    {
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update success");
                        pimService.DeleteMealPlanDetail(mealPlan.MealPlanID);
                        if (arrayRecipeId != null && arrayRecipeId.Length > 0)
                        {
                            for (int i = 0; i < arrayRecipeId.Length; i++)
                            {
                                if (!string.IsNullOrEmpty(arrayRecipeId[i]))

                                    pimService.InsertPlanItMealDetail(mealPlan.MealPlanID, 1, Convert.ToInt32(arrayRecipeId[i]), 0, 1, 0, DateTime.Now, "", mealPlan.UserID.ToString());
                            }

                            //Insert
                        }
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                        Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                        Response.Redirect("MyMealPlan.aspx");
                        //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated MealPlan Successful')", true);
                    }
                    else
                    {
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update fail");
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                        Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                        ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update MealPlan')", true);
                    }
                }
                else
                {
                    logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update meal plan from other meal plan");
                    List<PIM.API.MealPlan> lMealPlanOfUser = pimService.GetMealPlan(_MealPlanId.ToString(), _idUser.ToString());
                    if (lMealPlanOfUser != null && lMealPlanOfUser.Count > 0)
                    {
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Meal plan is avalable");
                        PIM.API.MealPlan mealPlanOfUser = lMealPlanOfUser[0];
                        if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                        {
                            if (File.Exists(Server.MapPath(mealPlan.MealPlanPhoto)))
                            {
                                File.Delete(Server.MapPath(mealPlan.MealPlanPhoto));

                            }
                            string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                            location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                            path = pathSave + "/" + nextID + fn;
                            try
                            {
                                System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                                if (image.Size.Width > 700)
                                {
                                    Common1.ResizeImage(image, 700, location);
                                }
                                else
                                {
                                    Common1.ResizeImage(image, image.Size.Width, location);
                                }
                            }
                            catch (Exception ex)
                            {
                                Response.Write("Error: " + ex.Message);
                            }
                        }
                        else
                        {
                            path = mealPlan.MealPlanPhoto;
                        }
                        //if (string.IsNullOrEmpty(hdImage.Value))
                        //{
                        //    hdImage.Value = mealPlan.MealPlanPhoto;
                        //}
                        string result = pimService.UpdateMealPlan(mealPlanOfUser.MealPlanID, mealPlanOfUser.UserID, mealPlanOfUser.CreatedUserID,
                                mealPlanOfUser.ParentUserId, txtMealPlanName.Text, mealPlanOfUser.isShared, mealPlanOfUser.canCopy, mealPlanOfUser.NoOfReview,
                                mealPlanOfUser.MealPlanRating, mealPlanOfUser.AvgCalPerDay,
                            mealPlanOfUser.EstCostPerDay, path, txtDescription.Text, txtBasic.Text);

                        Image2.Src = "/" + path;
                        if (result.Equals("True"))
                        {
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update success");
                            pimService.DeleteMealPlanDetail(mealPlanOfUser.MealPlanID);
                            if (arrayRecipeId != null && arrayRecipeId.Length > 0)
                            {
                                for (int i = 0; i < arrayRecipeId.Length; i++)
                                {
                                    if (!string.IsNullOrEmpty(arrayRecipeId[i]))
                                        pimService.InsertPlanItMealDetail(mealPlan.MealPlanID, 1, Convert.ToInt32(arrayRecipeId[i]), 0, 1, 0, DateTime.Now, "", mealPlanOfUser.UserID.ToString());
                                }

                                //Insert
                            }
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                            Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                            Response.Redirect("MyMealPlan.aspx");
                            //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated MealPlan Successful')", true);
                        }
                        else
                        {
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Update fail");
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                            Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update MealPlan')", true);
                        }
                    }
                    else
                    {
                        logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Meal plan is not avalable");
                        double rating = 5;
                        if (!string.IsNullOrEmpty(ratingStar.Value))
                            rating = Convert.ToDouble(ratingStar.Value);
                        //Insert New MealPlan
                        if ((fImageUpload.PostedFile != null) && (fImageUpload.PostedFile.ContentLength > 0))
                        {
                            string fn = System.IO.Path.GetFileName(fImageUpload.PostedFile.FileName);
                            location = Server.MapPath(pathUpload) + "/" + nextID + fn;
                            path = pathSave + "/" + nextID + fn;
                            try
                            {
                                System.Drawing.Image image = System.Drawing.Image.FromStream(fImageUpload.PostedFile.InputStream);
                                if (image.Size.Width > 700)
                                {
                                    Common1.ResizeImage(image, 700, location);
                                }
                                else
                                {
                                    Common1.ResizeImage(image, image.Size.Width, location);
                                }
                            }
                            catch (Exception ex)
                            {
                                Response.Write("Error: " + ex.Message);
                            }
                        }
                        int mealPlanId = pimService.InsertPlanItMeal(_idUser, _idUser, _idUser, txtMealPlanName.Text, true, true, 4, 0, 0, path , 0, txtDescription.Text, txtBasic.Text);
                        //Insert Recipe
                        if (mealPlanId > -1)
                        {
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Insert is success");
                            if (arrayRecipeId != null && arrayRecipeId.Length > 0)
                            {
                                for (int i = 0; i < arrayRecipeId.Length; i++)
                                {
                                    if (!string.IsNullOrEmpty(arrayRecipeId[i]))
                                    {
                                        bool bResult = pimService.InsertPlanItMealDetail(mealPlanId, 1, Convert.ToInt32(arrayRecipeId[i]), 0, 1, 0, DateTime.Now, "", _idUser.ToString());
                                    }
                                }

                                //Insert
                                logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                                Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                                Response.Redirect("MyMealPlan.aspx");
                            }
                        }
                        else
                        {
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Insert is fail");
                            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
                            Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
                            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Create MealPlan')", true);
                        }

                    }
                }

            }

        }
        catch (Exception ex)
        {
            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] Error: " + ex.Message);
            logSave.AppendLine("[" + DateTime.Now.ToShortDateString() + "][Save Meal Plan] End");
            Common.Logger.WriteLog(logSave.ToString(), "MealPlanDetail");
        }


    }


    protected void btn_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
        try
        {
            if (panel2.Visible)
            {
                btnEdit.ImageUrl = "images/btn_cancel.jpg";
                btnUpload.Visible = true;
                //GetRecipeUser(_RecipeId);
                btnSave.Visible = true;
                panel1.Visible = true;
                panel2.Visible = false;
                panel3.Visible = false;
                panel4.Visible = true;
                if (Session["Userid"].ToString() == checkUser.Value)
                {
                    btnDelete.Visible = true;
                }
            }
            else
            {
                btnEdit.ImageUrl = "images/btn_edit.jpg";
                btnUpload.Visible = false;
                btnSave.Visible = false;
                panel1.Visible = false;
                panel2.Visible = true;
                panel3.Visible = true;
                panel4.Visible = false;
                btnDelete.Visible = false;
            }
        }
        catch (Exception ex)
        {

        }
    }
    protected void btnDelete_Click1(object sender, EventArgs e)
    {
        
        bool result = false;
        try
        {
            PIM.API.MealPlan mealPlan = pimService.GetMealPlanByMealPlanId(_MealPlanId.ToString());
            if (File.Exists(Server.MapPath("../" + mealPlan.MealPlanPhoto)))
            {
                File.Delete(Server.MapPath("../" + mealPlan.MealPlanPhoto));

            }
            result = Convert.ToBoolean(pimService.DeletMealPlan(_MealPlanId));

        }
        catch (Exception ex)
        {

        }
        if (result)
        {
            Response.Redirect("MyMealPlan.aspx");
        }
        else
        {
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "Rating()", true);
            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Delete MealPlan')", true);
        }
    }

    private void shareGoogle()
    {
        lnkGoogle.HRef = "https://plus.google.com/share?url=" + Request.Url.AbsoluteUri;
    }

   
}